﻿'© 2004 - 2010 ActiveModules, Inc. All Rights Reserved
Imports Microsoft.ApplicationBlocks.Data
Imports System.Xml
Imports System.Web

Namespace DotNetNuke.Modules.ActiveForums.Data
    Public Class ForumsDB
        Inherits DataConfig
        Public Function Forum_GetByTopicId(ByVal TopicId As Integer) As Integer
            Return CType(SqlHelper.ExecuteScalar(_connectionString, dbPrefix & "ForumGetByTopicId", TopicId), Integer)
        End Function
        Public Function Forums_GetForSocialGroup(ByVal PortalId As Integer, ByVal SocialGroupId As Integer) As IDataReader
            Return SqlHelper.ExecuteReader(_connectionString, dbPrefix & "GetForumsForSocialGroup", SocialGroupId)
        End Function
        'Public Function Forums_List(ByVal PortalId As Integer, ByVal ModuleId As Integer) As IDataReader
        '    Return SqlHelper.ExecuteReader(_connectionString, dbPrefix & "Forums_GetPermissions", PortalId, ModuleId)
        'End Function
        Public Function Forums_Get(ByVal PortalId As Integer, ByVal ModuleId As Integer, ByVal ForumId As Integer) As IDataReader
            Return SqlHelper.ExecuteReader(_connectionString, dbPrefix & "ForumGet", PortalId, ModuleId, ForumId)
        End Function
        Public Function Forums_List(ByVal PortalId As Integer, ByVal ModuleId As Integer, ByVal ForumGroupId As Integer, ByVal ParentForumId As Integer, ByVal FillLastPost As Boolean) As IDataReader
            Return CType(SqlHelper.ExecuteReader(_connectionString, dbPrefix & "Forums_List", ModuleId, ForumGroupId, ParentForumId, FillLastPost), IDataReader)
        End Function
        Public Function Forums_List(ByVal PortalId As Integer, ByVal ModuleId As Integer) As ForumCollection
            Dim f As New ForumCollection
            Dim obj As Object = DataCache.CacheRetrieve(String.Format(CacheKeys.ForumList, ModuleId))
            If Not obj Is Nothing Then
                f = CType(obj, ForumCollection)
            Else
                Using dr As IDataReader = SqlHelper.ExecuteReader(_connectionString, dbPrefix & "ForumsList", PortalId, ModuleId)

                    Dim fi As Forum = Nothing
                    Dim gi As ForumGroupInfo = Nothing
                    While dr.Read
                        fi = New Forum
                        gi = New ForumGroupInfo
                        With fi
                            .ModuleId = Integer.Parse(dr("ModuleId").ToString)
                            .ForumID = CInt(dr("ForumId").ToString)
                            .Active = Boolean.Parse(dr("Active").ToString)
                            .ForumDesc = dr("ForumDesc").ToString
                            .ForumGroupId = Integer.Parse(dr("ForumGroupId").ToString)
                            .ForumID = Integer.Parse(dr("ForumId").ToString)
                            .ForumName = dr("ForumName").ToString
                            .GroupName = dr("GroupName").ToString
                            .Hidden = Boolean.Parse(dr("Hidden").ToString)
                            .ParentForumId = CInt(dr("ParentForumId").ToString)
                            If Not Date.TryParse(dr("LastPostDate").ToString, .LastPostDateTime) Then
                                .LastPostDateTime = Nothing
                            End If

                            .LastTopicId = Integer.Parse(dr("LastTopicId").ToString)
                            .LastReplyId = Integer.Parse(dr("LastReplyId").ToString)
                            .LastPostSubject = dr("LastPostSubject").ToString
                            .LastPostDisplayName = dr("LastPostAuthorName").ToString
                            .LastPostUserID = Integer.Parse(dr("LastPostAuthorId").ToString)
                            .LastPostUserName = .LastPostDisplayName
                            .LastRead = Date.Parse(dr("LastRead").ToString)
                            gi.Active = Boolean.Parse(dr("GroupActive").ToString)
                            gi.Hidden = Boolean.Parse(dr("GroupHidden").ToString)
                            gi.GroupName = .GroupName
                            gi.ForumGroupId = .ForumGroupId
                            gi.PrefixURL = dr("GroupPrefixURL").ToString
                            'gi.SEO = dr("GroupSEO").ToString
                            .ForumGroup = gi
                            With .Security
                                .Announce = dr("CanAnnounce").ToString
                                .Attach = dr("CanAttach").ToString
                                .Create = dr("CanCreate").ToString
                                .Delete = dr("CanDelete").ToString
                                .Edit = dr("CanEdit").ToString
                                .Lock = dr("CanLock").ToString
                                .ModApprove = dr("CanModApprove").ToString
                                .ModDelete = dr("CanModDelete").ToString
                                .ModEdit = dr("CanModEdit").ToString
                                .ModLock = dr("CanModLock").ToString
                                .ModMove = dr("CanModMove").ToString
                                .ModPin = dr("CanModPin").ToString
                                .ModSplit = dr("CanModSplit").ToString
                                .ModUser = dr("CanModUser").ToString
                                .Pin = dr("CanPin").ToString
                                .Poll = dr("CanPoll").ToString
                                .Block = dr("CanBlock").ToString
                                .Read = dr("CanRead").ToString
                                .Reply = dr("CanReply").ToString
                                .Subscribe = dr("CanSubscribe").ToString
                                .Trust = dr("CanTrust").ToString
                                .View = dr("CanView").ToString
                            End With
                            .ForumSettings = LoadSettings(dr)
                            .PrefixURL = dr("PrefixURL").ToString
                            '.SEO = dr("ForumSEO").ToString
                            .TotalTopics = Integer.Parse(dr("TotalTopics").ToString)
                            .TotalReplies = Integer.Parse(dr("TotalReplies").ToString)
                        End With
                        f.Add(fi)
                    End While
                    dr.Close()
                End Using

                DataCache.CacheStore(String.Format(CacheKeys.ForumList, ModuleId), f)
            End If
            Return f

        End Function
        Private Function LoadSettings(ByVal dr As IDataRecord) As Hashtable
            Dim ht As New Hashtable
            Dim snames As String = "ALLOWATTACH,ALLOWEMOTICONS,ALLOWHTML,ALLOWPOSTICON,ALLOWRSS,ALLOWSCRIPT,ALLOWTAGS,ATTACHCOUNT,ATTACHMAXHEIGHT,ATTACHMAXSIZE,ATTACHMAXWIDTH,ATTACHSTORE,ATTACHTYPEALLOWED,ATTACHUNIQUEFILENAMES,AUTOSUBSCRIBEENABLED,AUTOSUBSCRIBENEWTOPICSONLY,AUTOSUBSCRIBEROLES,AUTOTRUSTLEVEL,DEFAULTTRUSTLEVEL,EDITORHEIGHT,EDITORPERMITTEDUSERS,EDITORSTYLE,EDITORTOOLBAR,EDITORTYPE,EDITORWIDTH,EMAILADDRESS,INDEXCONTENT,ISMODERATED,MCADDRESS,MCADMINNOTIFY,MCAUTOCREATEUSERS,MCAUTORESPONSE,MCENABLED,MCEOMTAG,MCEOMTAGREQ,MCMODTYPE,MCPOPPASSWORD,MCPOPSERVER,MCPOPUSERNAME,MCREJECTNOTIFY,MCRESTRICTALIAS,MCSTRIPHTML,MCSUBNOTIFY,MCURL,MODAPPROVETEMPLATEID,MODDELETETEMPLATEID,MODMOVETEMPLATEID,MODNOTIFYTEMPLATEID,MODREJECTTEMPLATEID,PROFILETEMPLATEID,QUICKREPLYFORMID,REPLYFORMID,TOPICFORMID,TOPICSTEMPLATEID,TOPICTEMPLATEID,USEFILTER"
            Dim SettingKeys() As String = snames.Split(CChar(","))
            For Each s As String In SettingKeys
                If Not dr.GetOrdinal(s) = Nothing Then
                    ht.Add(s, dr(s))
                End If
            Next
            Return ht
        End Function
        Public Function ForumListXML(ByVal SiteId As Integer, ByVal InstanceId As Integer) As XmlDocument
            Dim xDoc As New XmlDocument
            Dim obj As Object = DataCache.CacheRetrieve(InstanceId & "fv")
            If obj Is Nothing Then
                Dim db As New Data.ForumsDB
                Dim fc As ForumCollection = db.Forums_List(SiteId, InstanceId)
                'Dim ds As DataSet = SqlHelper.ExecuteDataset(connectionString, databaseOwner & objectQualifier & "activeforums_UI_ForumDisplay", SiteId, InstanceId, UserId, -1, ForumIds)
                Dim sb As New Text.StringBuilder
                sb.Append("<?xml version=""1.0"" encoding=""utf-8"" ?>")
                sb.AppendLine()
                sb.Append("<root>")
                sb.AppendLine()
                Dim groupId As Integer = -1
                Dim groups As New Text.StringBuilder
                Dim forums As New Text.StringBuilder
                For Each f As Forum In fc
                    If groupId <> f.ForumGroupId Then
                        groups.Append("<group groupid=""" & f.ForumGroupId.ToString & """ active=""" & f.ForumGroup.Active.ToString.ToLowerInvariant & """ hidden=""" & f.ForumGroup.Hidden.ToString.ToLowerInvariant & """>")
                        groups.Append("<name><![CDATA[" & f.GroupName.ToString & "]]></name>")
                        'If Not String.IsNullOrEmpty(f.ForumGroup.SEO) Then
                        '    groups.Append(f.ForumGroup.SEO)
                        'End If
                        groups.Append("</group>")
                        sb.AppendLine()
                        groupId = f.ForumGroupId
                    End If
                Next
                sb.Append("<groups>")
                sb.AppendLine()
                sb.Append(groups.ToString)
                sb.Append("</groups>")
                sb.AppendLine()
                For Each f As Forum In fc
                    forums.Append("<forum groupid=""" & f.ForumGroupId.ToString & """ forumid=""" & f.ForumID.ToString & """")
                    'forums.Append(" name=""" & HttpUtility.UrlEncode(f.ForumName) & """")
                    'forums.Append(" desc=""" & HttpUtility.UrlEncode(Utilities.HTMLEncode(f.ForumDesc.ToString)) & """")
                    forums.Append(" active=""" & f.Active.ToString.ToLowerInvariant & """")
                    forums.Append(" hidden=""" & f.Hidden.ToString.ToLowerInvariant & """")
                    forums.Append(" totaltopics=""" & f.TotalTopics.ToString & """")
                    forums.Append(" totalreplies=""" & f.TotalReplies.ToString & """")
                    forums.Append(" lasttopicid=""" & f.LastTopicId.ToString & """")
                    forums.Append(" lastreplyid=""" & f.LastReplyId.ToString & """")
                    'forums.Append(" lastpostsubject=""" & f.LastPostSubject & """")
                    'forums.Append(" lastpostauthorname=""" & f.LastPostDisplayName & """")
                    forums.Append(" lastpostauthorid=""" & f.LastPostUserID & """")
                    forums.Append(" lastpostdate=""" & f.LastPostDateTime.ToString & """")
                    forums.Append(" lastread=""" & f.LastRead.ToString & """")
                    forums.Append(" allowrss=""" & f.ForumSettings("ALLOWRSS").ToString & """")
                    forums.Append(" parentforumid=""" & f.ParentForumId.ToString & """")
                    forums.Append(" viewroles=""" & f.Security.View.ToString & """")
                    forums.Append(" readroles=""" & f.Security.Read.ToString & """")
                    forums.Append(" replyroles=""" & f.Security.Reply.ToString & """")
                    forums.Append(" modroles=""" & f.Security.ModApprove.ToString & """")
                    forums.Append(" modmove=""" & f.Security.ModMove.ToString & """")
                    forums.Append(">")
                    forums.Append("<name><![CDATA[" & f.ForumName & "]]></name>")
                    forums.Append("<description><![CDATA[" & f.ForumDesc & "]]></description>")
                    forums.Append("<security>")
                    forums.Append("<view>" & f.Security.View & "</view>")
                    forums.Append("<read>" & f.Security.Read & "</read>")
                    forums.Append("<create>" & f.Security.Create & "</create>")
                    forums.Append("<reply>" & f.Security.Reply & "</reply>")
                    forums.Append("<edit>" & f.Security.Edit & "</edit>")
                    forums.Append("<delete>" & f.Security.Delete & "</delete>")
                    forums.Append("<lock>" & f.Security.Lock & "</lock>")
                    forums.Append("<pin>" & f.Security.Pin & "</pin>")
                    forums.Append("<modapprove>" & f.Security.ModApprove & "</modapprove>")
                    forums.Append("<modedit>" & f.Security.ModEdit & "</modedit>")
                    forums.Append("<moddelete>" & f.Security.ModDelete & "</moddelete>")
                    forums.Append("<modlock>" & f.Security.ModLock & "</modlock>")
                    forums.Append("<modpin>" & f.Security.ModPin & "</modpin>")
                    forums.Append("<modmove>" & f.Security.ModMove & "</modmove>")
                    forums.Append("</security>")
                    'If Not String.IsNullOrEmpty(f.SEO) Then
                    '    forums.Append(f.SEO)
                    'End If

                    forums.Append("</forum>")
                    sb.AppendLine()
                Next
                sb.Append("<forums>")
                sb.AppendLine()
                sb.Append(forums.ToString)
                sb.Append("</forums>")
                sb.AppendLine()
                sb.Append("<topics />")
                sb.AppendLine()
                sb.Append("<replies />")
                sb.AppendLine()
                sb.Append("</root>")
                sb.AppendLine()


                'Dim sXML As String = ds.GetXml()
                xDoc.LoadXml(sb.ToString)
                DataCache.CacheStore(InstanceId & "fv", xDoc)
            Else
                xDoc = CType(obj, XmlDocument)
            End If
            'Logger.Log(xDoc.OuterXml)
            Return xDoc
        End Function
    End Class
End Namespace
